//
//  WSLessonTickedViewController.m
//  WisdomStar
//
//  Created by 谭飞 on 2018/10/30.
//  Copyright © 2018年 zhangliwen. All rights reserved.
//

#import "WSLessonTickedViewController.h"
#import "WSLessonTicketAlertView.h"
#import "WSLessonTicketCell.h"

#import "MyService.h"
#import "LessonTicketInfo.h"
#import "ScoreInfo.h"

@interface WSLessonTickedViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalLab; // 总的课时券、积分数量
@property (weak, nonatomic) IBOutlet UIButton *exchangeBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) WSLessonTicketAlertView *alertView;

// data source
@property (nonatomic, strong) NSArray <ScoreInfo *> *scoreDatas;
@property (nonatomic, strong) NSArray <LessonTicketInfo *> *ticketDatas;

@property (nonatomic, assign) NSInteger pageNo; //分页
@property (nonatomic, assign) BOOL hasNext; // 是否有分页

@end

@implementation WSLessonTickedViewController

#pragma mark - Life cycle
- (void)dealloc {
    NSLog(@"%s",__func__);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
    [self setupRefreshControl];
}

- (void)setup {
    self.titleLabel.text = _pageType == Ticket ? @"当前课时券" : @"当前积分";
    [self.exchangeBtn setCorners:UIRectCornerAllCorners cornerRadius:self.exchangeBtn.xmg_height];
    
    self.tableView.tableFooterView = [UIView new];
    // regist cells
    [self.tableView registerNib:[UINib nibWithNibName:[WSLessonTicketCell className] bundle:nil] forCellReuseIdentifier:[WSLessonTicketCell className]];
}

- (void)setupRefreshControl {
    WEAKSELF
    [self.tableView mh_addHeaderRefresh:^(MJRefreshNormalHeader *header) {
        [weakSelf loadData];
    }];
    [self.tableView.mj_header beginRefreshing];
}

- (void)loadData {
    if (_pageType == Ticket) { // 获取我的课时券
        [MyService fetchLessonTicketWithResult:^(id  _Nonnull responseObj) {
            [self.tableView.mj_header endRefreshing];
            ResponseModel *response = [ResponseModel yy_modelWithJSON:responseObj];
            if (!response.data) {
                return ;
            }
            self.ticketDatas = [NSArray yy_modelArrayWithClass:[LessonTicketInfo class] json:response.data[@"data"]];
            self.totalLab.text = [NSString stringWithFormat:@"%@",@([response.data[@"course"] integerValue])];
            [self.tableView reloadData];
        }];
        
    } else { // 获取我的积分
        [MyService fetchMyScoresWithResult:^(id  _Nonnull responseObj) {
            [self.tableView.mj_header endRefreshing];
            ResponseModel *response = [ResponseModel yy_modelWithJSON:responseObj];
            if (!response.data) {
                return ;
            }
            self.scoreDatas = [NSArray yy_modelArrayWithClass:[ScoreInfo class] json:response.data[@"data"]];
            self.totalLab.text = [NSString stringWithFormat:@"%@",@([response.data[@"score"] integerValue])];
            [self.tableView reloadData];
        }];
    }
}

// load more
- (void)loadMoreData {
    WEAKSELF
    [self.tableView mh_addFooterRefresh:^(MJRefreshAutoNormalFooter *footer) {
        weakSelf.pageNo += 1;
        if (weakSelf.hasNext) {
            
        } else {
            [footer endRefreshingWithNoMoreData];
        }
    }];
}

#pragma mark - 兑换
- (IBAction)exchangeBtnClick:(id)sender {
    WEAKSELF
    self.alertView.confirmBlock = ^(WSLessonTicketAlertView * _Nonnull alert, NSString * _Nonnull numStr) {
        if (numStr.length == 0) {
            [weakSelf showHint:@"请输入兑换数量"];
            return ;
        }
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        dic[@"token"] = User_Token;
        dic[@"score"] = numStr;
        [MyService exchangeWithParams:dic completion:^(BOOL success) {
            [alert hide];
            if (success) {
                [SVProgressHUD showSuccess:@"兑换成功"];
            }
        }];
    };
    [self.alertView show];
}

#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _pageType == Ticket ? self.ticketDatas.count : self.scoreDatas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WSLessonTicketCell *cell = [tableView dequeueReusableCellWithIdentifier:[WSLessonTicketCell className] forIndexPath:indexPath];
    cell.titleLabel.text = _pageType == Ticket
    ? self.ticketDatas[indexPath.row].explain
    : self.scoreDatas[indexPath.row].explain;
    cell.timeLab.text = _pageType == Ticket
    ? self.ticketDatas[indexPath.row].create_at
    : self.scoreDatas[indexPath.row].create_at;
    cell.numberLab.text = _pageType == Ticket
    ? [NSString stringWithFormat:@"%@",@(self.ticketDatas[indexPath.row].num)]
    : [NSString stringWithFormat:@"%@",@(self.scoreDatas[indexPath.row].number)];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

#pragma mark - Getter

- (WSLessonTicketAlertView *)alertView {
    if (_alertView == nil) {
        _alertView = [[WSLessonTicketAlertView alloc] init];
        _alertView.type = self.pageType;
    }
    return _alertView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
